from django.db import transaction
from django.db.models import Q, Count
from rest_framework import filters, status
from rest_framework.decorators import action
from rest_framework.response import Response

from apps.common.models import Pagination, Personal_Center_Region_Pagination
from apps.common.permissions import GzdePermission
from apps.personal_center.filters import AddressFilter, OrdersFilter, Order_EvaluatesFilter, Construction_TeamsFilter
from apps.personal_center.models import Personal_Center_Region, Address, Order_ScenePhoto, Order, Order_ScenePhoto_temp, \
    Order_Evaluate, Construction_Team
from apps.personal_center.serializers import Personal_Center_RegionSerializer, AddressSerializer, \
    Order_ScenePhotosSerializer, OrdersSerializer, Order_ScenePhotosTempSerializer, Order_EvaluatesSerializer, \
    Construction_TeamsSerializer
from extensions.viewsets import *
from extensions.permissions import IsAuthenticated

class Personal_Center_RegionViewSet(ModelViewSet, ExportMixin, ImportMixin):
    """省市县区管理"""
    serializer_class = Personal_Center_RegionSerializer
    pagination_class = Personal_Center_Region_Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter)
    search_fields = ['name']
    select_related_fields = ['parent']
    ordering_fields = ['sort']

    def get_queryset(self):
        # base_query = Q(parent__isnull=True)
        base_query = Q(level=1)
        personal_center_region = Personal_Center_Region.objects.filter(base_query)

        return personal_center_region


class Personal_Center_AddressViewSet(ModelViewSet):
    """Address"""
    serializer_class = AddressSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = AddressFilter
    search_fields = ['name','phone']
    select_related_fields = ['province', 'user',]
    ordering_fields = ['id', 'name', 'create_time']

    def get_queryset(self):
        # 获取当前用户
        user = self.request.user
        # 按照是否为默认地址降序排序，然后按照创建时间升序排序
        # 这样默认地址会排在第一位，其他地址按照创建时间排列
        queryset = Address.objects.filter(user=user,del_flag=False).order_by('-is_default', 'create_time')
        return queryset

    def filter_queryset(self, queryset):
        # 确保不论前端请求如何，都先按照默认地址排序
        queryset = super().filter_queryset(queryset)
        return queryset.order_by('-is_default', 'create_time')

    # 在返回列表中添加默认地址
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        statistic = queryset.aggregate(count=Count('id'))

        # 获取默认地址
        default_address = Address.objects.filter(user=request.user, is_default=True).first()
        default_address_id = default_address.id if default_address else None

        # 分页处理
        queryset = self.paginate_queryset(queryset)
        if queryset is not None:
            serializer = self.get_serializer(queryset, many=True)
            result = serializer.data
            # 添加默认地址标记
            if default_address:
                for i in result:
                    i['is_default'] = (i['id'] == default_address_id)
            # 在分页响应中添加 default_address_id 字段
            data = {
                "count": statistic['count'],
                'defaultId': default_address_id,
                'results': result
            }
            return Response(data=data, status=status.HTTP_200_OK)

        # 如果没有分页，直接返回数据
        serializer = self.get_serializer(queryset, many=True)
        data = {
            "count": statistic['count'],
            'defaultId': default_address_id,
            'results': serializer.data
        }
        return Response(data=data, status=status.HTTP_200_OK)

    @action(detail=False, methods=['post'])
    def setDefault(self, request):
        """设置默认地址"""
        id = request.data['id']
        Address.objects.filter(user=request.user).update(is_default=False)
        res = Address.objects.filter(id=id).update(is_default=True)#
        result={"status": "success", "msg": "设置成功", "data": res}
        return Response(data=result, status=status.HTTP_200_OK)

    @action(detail=False, methods=['post'])
    def delete_Address(self, request):
        """删除所选"""
        id = request.data.get('id')  # 获取地址ID
        try:
            # 获取要删除的地址对象
            address_to_delete = Address.objects.get(id=id)
        except Address.DoesNotExist:
            return Response({"status": "error", "msg": "地址不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 检查是否为默认地址
        if address_to_delete.is_default:
            # 将地址标记为已删除
            address_to_delete.del_flag = True
            address_to_delete.is_default = False
            address_to_delete.save()

            # 从未删除的地址中获取最新的地址
            new_default_address = Address.objects.filter(
                user=request.user,
                del_flag=False
            ).exclude(id=id).order_by('-create_time').first()

            # 如果存在，则设置为新的默认地址
            if new_default_address:
                new_default_address.is_default = True
                new_default_address.save()
        else:
            # 如果不是默认地址，直接标记为已删除
            address_to_delete.del_flag = True
            address_to_delete.save()

        result = {"status": "success", "msg": "删除成功"}
        return Response(data=result, status=status.HTTP_200_OK)

    #获取默认地址
    @action(detail=False, methods=['get'])
    def get_default_address(self, request):
        default_address = Address.objects.filter(user=request.user, is_default=True).first()
        serializer = self.get_serializer(default_address)
        return Response(serializer.data, status=status.HTTP_200_OK)
    


class Order_ScenePhotosTempViewSet(ModelViewSet):
    """预约订单现场图片"""
    serializer_class = Order_ScenePhotosTempSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    queryset = Order_ScenePhoto_temp.objects.all()

    @transaction.atomic
    def perform_destroy(self, instance):
        instance.file.delete(save=False)
        instance.delete()
        Response(status=status.HTTP_204_NO_CONTENT)
        

class OrdersViewSet(ModelViewSet):
    """OrdersViewSet"""
    serializer_class = OrdersSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = OrdersFilter
    search_fields = ['order_no','user']
    select_related_fields = ['user']
    ordering_fields = ['id', 'name', 'add_time']

    def get_queryset(self):
        # 根据权限添加额外的查询条件
        user = self.request.user
        if user.is_superuser:
            queryset = Order.objects.all()
        else:
            queryset = Order.objects.filter(user=user)
        return queryset

    #统计各种状态的订单数量
    @action(detail=False, methods=['get'])
    def get_status_counts(self, request):
        """统计各种状态的订单数量"""
        user = self.request.user
        # 获取原始查询集，考虑到超级用户可以看到所有订单
        if user.is_superuser:
            queryset = Order.objects.all()
        else:
            queryset = Order.objects.filter(user=user)

        # 获取所有可能的订单状态
        order_statuses = [status_order[0] for status_order in Order.ORDER_STATUS_CHOICES]

        # 初始化计数字典，每个状态的计数为0
        counts_by_status = {status_order: 0 for status_order in order_statuses}

        # 使用Django的聚合功能统计每种状态的订单数量
        status_counts = queryset.values('order_status').annotate(count=Count('order_status'))

        # 更新计数字典中的计数
        for entry in status_counts:
            counts_by_status[entry['order_status']] = entry['count']

        # 转换为字典方便查找
        counts_dict = {entry['order_status']: entry['count'] for entry in status_counts}

        # 构建最终结果，确保包括所有状态
        final_results = [
            {'order_status': status_order, 'count': counts_dict.get(status_order, 0)}
            for status_order in order_statuses
        ]

        # 返回统计结果
        return Response(data=final_results, status=status.HTTP_200_OK)

    @action(detail=False, methods=['post'])
    def cancel_order(self, request):
        """取消订单"""
        id = request.data.get('id')  # 获取地址ID
        try:
            # 获取要取消订单对象
            order = Order.objects.get(id=id)
        except Order.DoesNotExist:
            return Response({"status": "error", "msg": "订单不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 检查订单状态是否为'yiyuyue'
        if order.order_status == 'yiyuyue':
            # 将订单状态cancel
            order.order_status = 'cancel'
            order.save()

        result = {"status": "success", "msg": "删除成功"}
        return Response(data=result, status=status.HTTP_200_OK)

#     改变订单状态
    @action(detail=False, methods=['post'])
    def change_order_status(self, request):
        """改变订单状态"""
        id = request.data.get('id')
        order_status = request.data.get('order_status')
        try:
            # 获取要取消订单对象
            order = Order.objects.get(id=id)
            order.order_status = order_status
            order.save()
        except Order.DoesNotExist:
            return Response({"status": "error", "msg": "订单不存在"}, status=status.HTTP_404_NOT_FOUND)
        result = {"status": "success", "msg": "修改成功"}
        return Response(data=result, status=status.HTTP_200_OK)
    

class Order_EvaluatesViewSet(ModelViewSet):
    """Order_EvaluatesViewSet"""
    serializer_class = Order_EvaluatesSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Order_EvaluatesFilter
    search_fields = ['evaluate_content']
    select_related_fields = ['order']
    ordering_fields = ['id']
    queryset = Order_Evaluate.objects.all()


class Construction_TeamsViewSet(ModelViewSet):
    """Construction_TeamesViewSet"""
    serializer_class = Construction_TeamsSerializer
    pagination_class = Pagination
    permission_classes = [IsAuthenticated]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = Construction_TeamsFilter
    search_fields = ['name','industry', 'contact', 'contact_phone', 'id_card', 'contact_address', 'detail']
    select_related_fields = ['create_user', 'update_user']
    ordering_fields = ['id']
    queryset = Construction_Team.objects.all()




